package com.movie.service.impl;

import com.movie.entity.Movie;
import com.movie.exception.ResourceNotFoundException;
import com.movie.mapper.MovieMapper;
import com.movie.service.MovieService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import java.util.List;

@Service
public class MovieServiceImpl implements MovieService {

    @Autowired
    private MovieMapper movieMapper;

    @Override
    public List<Movie> getAllMovies() {
        return movieMapper.findAll();
    }

    @Override
    public Movie getMovieById(Long id) {
        Movie movie = movieMapper.findById(id);
        if (movie == null) {
            throw new ResourceNotFoundException("Movie not found with id: " + id);
        }
        return movie;
    }

    @Override
    public Movie addMovie(Movie movie) {
        Assert.notNull(movie, "Movie object cannot be null");
        Assert.hasText(movie.getTitle(), "Movie title cannot be empty");
        movieMapper.insert(movie);
        return movie;
    }

    @Override
    public Movie updateMovie(Movie movie) {
        Assert.notNull(movie, "Movie object cannot be null");
        Assert.notNull(movie.getId(), "Movie ID cannot be null for update");
        Movie existingMovie = movieMapper.findById(movie.getId());
        if (existingMovie == null) {
            throw new ResourceNotFoundException("Cannot update non-existent movie with id: " + movie.getId());
        }
        int updatedRows = movieMapper.update(movie);
        if (updatedRows == 0) {
            throw new RuntimeException("Failed to update movie with id: " + movie.getId());
        }
        return movieMapper.findById(movie.getId());
    }

    @Override
    public boolean deleteMovie(Long id) {
        Assert.notNull(id, "Movie ID cannot be null for delete");
        Movie existingMovie = movieMapper.findById(id);
        if (existingMovie == null) {
            throw new ResourceNotFoundException("Cannot delete non-existent movie with id: " + id);
        }
        int deletedRows = movieMapper.deleteById(id);
        return deletedRows > 0;
    }

    @Override
    public List<Movie> getMoviesByStatus(String status) {
        Assert.hasText(status, "Status cannot be empty");
        return movieMapper.findByStatus(status);
    }

    @Override
    public List<Movie> searchMovies(String title, String director, String status) {
        // 传递参数给 Mapper，由 Mapper 处理 null 或空字符串
        return movieMapper.search(title, director, status);
    }
} 